package cn.hj.domain.strategy.service.rule.chain.impl;

import cn.hj.domain.strategy.adapter.repository.IStrategyRepository;
import cn.hj.domain.strategy.model.entity.RuleActionEntity;
import cn.hj.domain.strategy.model.valobj.RuleLogicCheckTypeVO;
import cn.hj.domain.strategy.service.Armory.IStrategyDispatch;
import cn.hj.domain.strategy.service.Armory.StrategyArmoryDispatch;
import cn.hj.domain.strategy.service.rule.chain.AbstractLogicChain;
import cn.hj.domain.strategy.service.rule.chain.factory.DefaultChainFactory;
import cn.hj.domain.strategy.service.rule.filter.factory.DefaultLogicFactory;
import cn.hj.types.common.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * 权重责任链
 */
@Component("rule_weight")
@Slf4j
public class RuleWeightLogicChain extends AbstractLogicChain {
    @Resource
    private IStrategyRepository strategyRepository;

    @Resource
    private StrategyArmoryDispatch strategyDispatch;


    @Override
    public DefaultChainFactory.StrategyAwardVO logic(Long strategyId, String userId) {

        String ruleValue = strategyRepository.queryStrategyRuleValue(strategyId, ruleModels());

        //根据用户id查询用户抽奖消耗的积分，本章我们先写死，后续从数据库中查询
        Map<Long,String> analyticalValueGroup  = getAnalyticalValue(ruleValue);
        if (analyticalValueGroup.isEmpty()) {
            return null;
        }

        //转换key值，并默认排序
        ArrayList<Long> analyticalSoertedKeys = new ArrayList<>(analyticalValueGroup.keySet());
        analyticalSoertedKeys.sort(Long::compareTo);

        //2. 获取用户抽奖消耗积分
        int userScore = strategyRepository.queryActivityAccountTotalUseCount(userId,strategyId);
        // 3. 找出最小符合的值，也就是【4500 积分，能找到 4000:102,103,104,105】、【5000 积分，能找到 5000:102,103,104,105,106,107】
        Long nextValue = analyticalSoertedKeys.stream().filter(key -> key <= userScore).findFirst().orElse(null);

        if (null != nextValue){
            Integer awardId = strategyDispatch.getRandomAwardId(strategyId, analyticalValueGroup.get(nextValue));
            log.info("用户抽奖消耗积分：{}，命中的规则：{}，命中的奖品：{}", userScore, nextValue, awardId);
            return DefaultChainFactory.StrategyAwardVO.builder()
                    .awardId(awardId)
                    .logicModel(ruleModels())
                    .build();
        }
        return next().logic(strategyId, userId);
    }

    @Override
    protected String ruleModels() {
        return DefaultChainFactory.LogicModel.RULE_WIGHT.getCode();
    }

    private Map<Long, String> getAnalyticalValue(String ruleValue)  {
        //分割4000:102,103,104,105 5000:102,103,104,105,106,107 6000:102,103,104,105,106,107,108,109
        String[] split = ruleValue.split(Constants.SPACE);
        Map<Long, String> map = new HashMap<>();
        for (String s : split) {
            String[] split1 = s.split(Constants.COLON);
            if (split1.length == 2) {
                map.put(Long.valueOf(split1[0]), split1[1]);
            }else {
                throw new IllegalArgumentException("权重规则格式错误" + ruleValue);
            }
        }
        return map;
    }
}
